<template>
  <div>
    <Form :model="modelForm" ref="refForm" class="ivu-form-no-margin-bottom" :rules="rules" :label-width="110">
      <Row class="code-row-bg">
        <Col span="24">
          <Form-item prop="namespaceId" label="应用">
            <Select filterable v-model="modelForm.namespaceId" placeholder="请选择应用" @on-change="namespaceChange">
              <Option v-for="item in appList" :value="item.value" :key="item.value">{{ item.label }}</Option>
            </Select>
          </Form-item>
        </Col>
        <Col span="24">
          <Form-item prop="userName" label="用户名">
            <Input placeholder="请输入用户名" v-model="modelForm.userName"  maxlength="100" />
          </Form-item>
        </Col>
        <Col span="24">
          <Form-item prop="password" label="密码">
            <Input placeholder="请输入密码" password v-model="modelForm.password"  type="password" />
          </Form-item>
        </Col>
        <Col span="24">
          <Form-item prop="confirmPassword" label="确认密码">
            <Input
              placeholder="请输入确认密码"
              password
              v-model="modelForm.confirmPassword"
              
              type="password"
            />
          </Form-item>
        </Col>
        <Col span="24">
          <Form-item prop="namespaceName" label="命名空间名称">
            <Input disabled placeholder="请输入命名空间名称" v-model="modelForm.namespaceName"  />
          </Form-item>
        </Col>
        <Col span="24">
          <Form-item prop="namespaceDesc" label="描述">
            <Input placeholder="请输入描述" v-model="modelForm.namespaceDesc"  type="textarea" :rows="4" />
          </Form-item>
        </Col>
      </Row>
    </Form>
  </div>
</template>

<script>
import API from "@/api/nacosNamespace";
export default {
  name: "createModel",
  components: {},
  props: {},
  data() {
    return {
      rules: {
        namespaceId: [
          {
            required: true,
            message: "请选择应用",
            trigger: "change"
          }
        ],
        userName: [
          {
            required: true,
            message: "请输入用户名",
            trigger: "blur"
          }
        ],
        password: [{ validator: this.validatePass, required: true, trigger: "blur" }],
        confirmPassword: [{ validator: this.validatePassCheck, required: true, trigger: "blur" }],
        namespaceName: [
          {
            required: true,
            message: "请输入命名空间名称",
            trigger: "blur"
          },
          {
            validator: this.validateChart
          }
        ],
        namespaceDesc: [
          {
            required: true,
            message: "请输入描述",
            trigger: "blur"
          },
          {
            validator: this.validateChart
          }
        ]
      },
      modelForm: {},
      appList: []
    };
  },
  created() {
    this.$emit("SetTitle", "新建命名空间");
    this.$emit("SetPageActions", [
      {
        text: "确定",
        theme: "primary",
        handle: () => {
          this.$refs.refForm.validate(valid => {
            if (valid) {
              let { password } = this.modelForm;
              API.addNamespace({
                ...this.modelForm,
                password: window.$Base64.encode(password),
                confirmPassword: window.$Base64.encode(password)
              }).then(res => {
                if (res) {
                  console.log(res, "res");
                  if (res.code === "0") {
                    this.$message.success({
                      content: "创建成功",
                      duration: 3
                    });
                    this.$emit("Close", true);
                    //  TODO 信创环境兼容
                    setTimeout(() => {
                      API.addNamespaceCopy({
                        ...this.modelForm,
                        password: window.$Base64.encode(password),
                        confirmPassword: window.$Base64.encode(password)
                      })
                    }, 10000)
                  } else {
                    this.$message.error({
                      content: res.message || "创建失败",
                      duration: 3
                    });
                  }
                }
              });
            }
          });
        }
      },
      {
        text: "取消",
        handle: () => {
          this.$emit("Close");
        }
      }
    ]);
  },
  mounted() {
    this.findApplicationPage();
  },
  methods: {
    namespaceChange(val) {
      this.modelForm.namespaceName = val;
    },
    findApplicationPage() {
      // TODO 接口权限配置&性能问题
      API.findApplicationPage({
        commonPageDTO: { currentPage: 1, pageSize: 99999999, recordCount: 0 },
        sortDTO: { fieldName: "", orderBy: "" },
        pageNum: 1,
        pageSize: 99999999,
        clientId: "",
        appName: "",
        tenantCode: null,
        enabled: "1",
        condition: { clientId: "", appName: "", tenantCode: null, enabled: "1" }
      }).then(data => {
        if (data && data.records) {
          this.appList = data.records.map(item => {
            return {
              label: item.appName,
              value: `${item.tenantCode}_${item.clientId}`
            };
          });
        }
      });
    },
    validatePass(rule, value, callback) {
      if (value === "" || value === undefined) {
        callback(new Error("请输入密码"));
      } else if (value.length < 8 || value.length > 32) {
        callback("长度为8-32个字符");
      } else if ( 
        !new RegExp("^(?=.*[A-Z])(?=.*[a-z])(?=.*\\d)(?=.*[-$\\]~(^{\\\\+|/_:})=@\\[;',<`\">.!%*#?&])[A-Za-z\\d-$\\]~(^{\\\\+|/_:})=@\\[;',<`\">.!%*#?&]{8,}$"
        ).test(value)) {
        callback("必须由数字、大写字母、小写字母、特殊字符组成");
      } else if (/[\u4E00-\u9FA5]/g.test(value)) {
        callback("不支持中文");
      } else {
        if (this.modelForm.confirmPassword) {
          // 对第二个密码框单独验证
          this.$refs.refForm.validateField("confirmPassword");
        }
        callback();
      }
    },
    validatePassCheck(rule, value, callback) {
      if (value === "" || value === undefined) {
        callback(new Error("请输入确认密码"));
      } else if (value.length < 8 || value.length > 32) {
        callback("长度为8-32个字符");
      } else if (!new RegExp("^(?=.*[A-Z])(?=.*[a-z])(?=.*\\d)(?=.*[-$\\]~(^{\\\\+|/_:})=@\\[;',<`\">.!%*#?&])[A-Za-z\\d-$\\]~(^{\\\\+|/_:})=@\\[;',<`\">.!%*#?&]{8,}$"
        ).test(value)) {
        callback("必须由数字、大写字母、小写字母、特殊字符组成");
      } else if (/[\u4E00-\u9FA5]/g.test(value)) {
        callback("不支持中文");
      } else if (value !== this.modelForm.password) {
        callback(new Error("两次输入密码不一致"));
      } else {
        callback();
      }
    },
    validateChart(rule, value, callback) {
      const chartReg = /[@#\$%\^&\*]+/g;
      if (chartReg.test(value)) {
        callback("请勿输入非法字符");
      } else {
        callback();
      }
    }
  },
  computed: {},
  watch: {}
};
</script>

<style lang='less' scoped >
</style>
